<template>
  <div class="middle-container" :style="{backgroundImage: bgImg, color: '#38E5DE'}">
    <div class="title-container">
      <div class="title">
        <img src="../../../assets/img/common/title_tip.png" height="16" width="16" />
        <div class="title-text">{{ title }}</div>
      </div>
      <img src="../../../assets/img/common/close-16px.png" style="cursor: pointer" @click="closeWindow" height="16"
        width="16" />
    </div>
    <div class="search-container" v-show="!showDetail">
      <span>日期：</span>
      <el-date-picker v-model="dateRange" type="daterange" range-separator="-" start-placeholder="开始日期"
        end-placeholder="结束日期" @change="handleSearch">
      </el-date-picker>
      <el-button type="primary" class="search-btn" @click="handleSearch">查询</el-button>
    </div>
    <div class="content-container" id="container" v-show="!showDetail">
      <div id="container" ref="treeChart"></div>
    </div>
  </div>
</template>
<script>
import { reactive, toRefs, onMounted, ref, defineComponent } from "vue";
import echartsUtil from "../../../commons/utils/echartsUtil";
import http from "@/commons/utils/httpUtil";
import dateUtil from "@/commons/utils/dateUtil";
// import {ElMessage} from "_element-plus@1.1.0-beta.24@element-plus";
import moment from 'moment';
import G6 from "@antv/g6";
// import mindmap from 'vue3-mindmap'
// import 'vue3-mindmap/dist/style.css'

export default defineComponent({
  name: 'ColdChain',
  //   components: { mindmap },
  setup() {
    const treeChart = ref(null)
    const state = reactive({
      dateRange: [moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'), moment(new Date()).format('YYYY-MM-DD')],
      bgImg: 'url(' + require('../../../assets/img/common/middle-bg.png') + ')',
      showDetail: false,
      title: '冷链溯源',
      treeData: {
        name: "南山冷冻冷藏品",
        normal: {
          backgroundColor: '#725bb8'
        },
        children: [
          {
            name: "南山港入境",
            children: [
              {
                name: "SCT蛇口港（20628.74吨）",
                children: [{ name: "CCT赤湾港（20628.74吨）", value: 0, dockCode: '赤湾码头', isDock: true, children: [] }, { name: "MCT妈湾港口（20628.74吨）", value: 0, dockCode: '妈湾保税港', isDock: true, children: [] }, { name: "SCT蛇口港dfdsfdsfdsfdsfdsfdsfdsfdsfdsfdsfdsfdsfdsfdsf", value: 0, children: [{name: "MCT妈湾港口（20628.74吨）", value: 0},{name: "MCT妈湾港口（20628.74吨）", value: 0},{ name: "MCT妈湾港口（20628.74吨）", value: 0, dockCode: '妈湾保税港', isDock: true, children: [] }, { name: "SCT我今儿个后期就会去问后期我和的顺丰到付的师傅的说法的", value: 0, children: [{name: "SCT对方看得就司法鉴定所法定就是傅的说法的", value: 0},{name: "SCT对方看得就司法鉴定所法定就是傅的说法的", value: 0},{ name: "SCT对方看得就司法鉴定所法定就是傅的说法的", value: 0, children: [{name: "SCT对方看得就司法鉴定所法定就是傅的说法的", value: 0},{ name: "SCT对方看得就司法鉴定所法定就是傅的说法的", value: 0, children: [{ name: "SCT对方看得就司法鉴定所法定就是傅的说法的", value: 0, children: [{ name: "SCT对方看得就司法鉴定所法定就是傅的说法的", value: 0, children: [{name: "SCT对方看得就司法鉴定所法定就是傅的说法的", value: 0},{ name: "SCT对方看得就司法鉴定所法定就是傅的说法的", value: 0, children: [{ name: "SCT对方看得就司法鉴定所法定就是傅的说法的", value: 0 }] }] }] }] }] }] }] }]
              },
              { name: "CCT赤湾港（20628.74吨）", value: 0, dockCode: '赤湾码头', isDock: true, children: [] },
              { name: "MCT妈湾港口（20628.74吨）", value: 0, dockCode: '妈湾保税港', isDock: true, children: [] },
            ],
          }
        ],
      },
      myChart: null,
      oldIdss: {},
      current_dep: 0
    })
    const closeWindow = () => {
      if (state.showDetail) {
        state.title = '冷链溯源'
        state.showDetail = !state.showDetail
      } else {
        window.AC.HideWindow(6, {});
      }
    }

    const initMap = () => {
      G6.registerNode(
        'tree-node',
        {
          options: {
            size: [60, 20], // 宽高
            stroke: '#91d5ff', // 变颜色
            fill: '#fff'// 填充色
          },
          drawShape: function drawShape(cfg, group) {
            // 获取节点的配置
            const styles = this.getShapeStyle(cfg)
            const rect = group.addShape('rect', {
              attrs: {
                ...styles,
                fill: '#45a5e5',
                stroke: '#468dbb',
              },
              name: 'rect-shape',
            });
            // 20个字后换行
            const content = cfg.name.replace(/(.{18})/g, '$1\n');
            const text = group.addShape('text', {
              attrs: {
                text: content,
                textAlign: 'left',
                textBaseline: 'middle',
                fill: '#fff',
                lineHeight: 45,
                fontSize: 38,
              },
              name: 'text-shape',
            });
            const bbox = text.getBBox();
            const hasChildren = cfg.children && cfg.children.length > 0;
            rect.attr({
              x: -bbox.width / 2 - 6,
              y: -bbox.height / 2 - 4,
              width: bbox.width + (hasChildren ? 30 : 16),
              height: bbox.height + 30,
              zIndex: 3,
            });
            text.attr({
              x: -bbox.width / 2 + 5,
              y: 8,
            })
            if (hasChildren) {
              // 设计小圆点
              group.addShape('marker', {
                attrs: {
                  x: bbox.width / 2 + 16,
                  y: 0,
                  r: 6,
                  symbol: cfg.collapsed ? G6.Marker.expand : G6.Marker.collapse,
                  stroke: '#fff',
                  lineWidth: 2,
                },
                name: 'collapse-icon',
              });
            }
            return rect;
          },
          update: (cfg, item) => {
            const group = item.getContainer();
            const icon = group.find((e) => e.get('name') === 'collapse-icon');
            icon.attr('symbol', cfg.collapsed ? G6.Marker.expand : G6.Marker.collapse);
          },
        },
        'single-node',
      );

      const container = document.getElementById('container');
      const graph = new G6.TreeGraph({
        container: 'container',
        width: 1152,
        height: 600,
        fitView: true, // 是否开启画布自适应。开启后图自动适配画布大小。
        fitViewPadding: [10, 20], // fitView 为 true 时生效。图适应画布时，指定四周的留白。
        minZoom: 0.2, // 最小缩放比例
        maxZoom: 10, // 最大缩放比例

        modes: {
          default: [
            {
              type: 'collapse-expand',
              onChange: function onChange(item, collapsed) {
                const data = item.get('model');
                graph.updateItem(item, {
                  collapsed,
                });
                data.collapsed = collapsed;
                return true;
              },
            },
            'drag-canvas',
            'zoom-canvas',
          ],
        },
        defaultNode: {
          size: [120, 50],
          type: 'tree-node',
          anchorPoints: [
            [0, 0.5],
            [1, 0.5],
          ],
        },
        defaultEdge: {
          type: 'cubic-horizontal',
          style: {
            stroke: '#fff',
          },
        },
        layout: {
          type: 'compactBox',
          direction: 'H',
          getId: function getId(d) {
            return d.id;
          },
          getHeight: function getHeight() {
            return 180;
          },
          getWidth: function getWidth() {
            return 300;
          },
          getVGap: function getVGap() {
            return 60;
          },
          getHGap: function getHGap() {
            return 250;
          },
          getSide: () => {
            return 'right';
          },
        },
      });
      let centerX = 0;
      graph.node(function (node) {
        if (node.id === 'Modeling Methods') {
          centerX = node.x;
        }

        return {
          //   label: node.id,
          labelCfg: {
            position: 'right',

            offset: 0,
          },
        };
      });
      // fetch('https://gw.alipayobjects.com/os/antvdemo/assets/data/modeling-methods.json')
      //   .then((res) => res.json())
      //   .then((data) => {
      //     G6.Util.traverseTree(data, function (item) {
      //       item.id = item.name;
      //     });
      graph.data(state.treeData);
      graph.render();
      graph.fitView();
      //    默认展开两层节点，之后，重新渲染， 一开始没有渲染的时候，item.depth的属性不存在，不能拿来做判断。可以根据item.depth来设置要展开的几层节点。
      G6.Util.traverseTree(state.treeData, function (item) {
        if (item.depth > 1) {
          //collapsed为true时默认收起
          item.collapsed = true
        }
      })
      graph.data(state.treeData);
      graph.render();
      graph.fitView();
      graph.zoom(1)

      if (typeof window !== 'undefined')
        window.onresize = () => {
          if (!graph || graph.get('destroyed')) return;
          if (!container || !container.scrollWidth || !container.scrollHeight) return;
          graph.changeSize(container.scrollWidth, container.scrollHeight);
        };
    }

    const firstInitTree = () => {
      let data = { startDate: dateUtil.format(state.dateRange[0], 'yyyy-MM-DD'), endDate: dateUtil.format(state.dateRange[1], 'yyyy-MM-DD') };
      http.get('/large/queryThreeDockInfo', data).then((res) => {
        if (res && res.data) {
          state.treeData.children[0].children.forEach(item => {
            let findItem = res.data.find(find => find.dockCode === item.dockCode)
            item.value = findItem ? findItem.weight : 0
          })
        }
        initMap()
      });
    }

    const handleSearch = () => {
      // firstInitTree()
    }




    // const queryChildList = (param) => {
    //   if (param.data.isDock) {
    //     let data = { dockCode: param.data.dockCode, startDate: dateUtil.format(state.dateRange[0], 'yyyy-MM-DD'), endDate: dateUtil.format(state.dateRange[1], 'yyyy-MM-DD') };
    //     http.post('/large/queryStockListByDockCode', data).then((res) => {
    //       if (res && res.data && res.data.length > 0) {
    //         setOption(param, res.data);
    //       } else {
    //         showMessage()
    //       }
    //     });
    //   } else {
    //     let idList = param.data.idListStr ? param.data.idListStr.split(',') : []

    //     if (idList.length === 0) {
    //       return
    //     }

    //     let data = { idList: idList, startDate: dateUtil.format(state.dateRange[0], 'yyyy-MM-DD'), endDate: dateUtil.format(state.dateRange[1], 'yyyy-MM-DD'), ioType: param.data.ioType };
    //     http.post('/large/queryStockListByIdList', data).then((res) => {
    //       if (res && res.data && res.data.length > 0) {
    //         setOption(param, res.data);
    //       } else {
    //         showMessage()
    //       }
    //     });
    //   }
    // }

    // const setOption = (param, data) => {
    //   data.forEach(item => {
    //     param.data.children.push({ name: item.entName + ',' + item.warehouseName, value: item.weight, children: [], ioType: item.ioType, idListStr: item.idListStr })
    //   })
    //   param.data.collapsed = false;
    //   let option = state.myChart.getOption();
    //   state.myChart.setOption(option);
    // }

    // const showMessage = () => {
    //   ElMessage({
    //     showClose: true,
    //     message: '暂无下一节点信息', // 此处可以换成接口返回的报错信息
    //     type: 'warning'
    //   });
    // }

    onMounted(() => {
      state.myChart = echartsUtil.initMyChart(treeChart.value)
      firstInitTree()
      initMap()
    })

    return {
      treeChart,
      //   treeData,
      state,
      ...toRefs(state),
      //   initMap,
      closeWindow,
      handleSearch,
    }
  },

})
</script>
<style>
.middle-container {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  height: 800px;
  width: calc(1200px - 48px);
  padding-left: 24px;
  padding-right: 24px;
}

.title-container {
  display: inline-flex;
  align-items: center;
  justify-content: space-between;
  height: 46px;
  width: 100%;
  font-size: 18px;
  font-weight: bold;
  border-bottom: 1px solid #38e5ed;
}

.title {
  display: inline-flex;
  align-items: center;
}

.title-text {
  margin-left: 5px;
}

.search-container {
  position: relative;
  color: #fff;
  margin: 20px 0;
  text-align: left;
}

.search-btn {
  margin-left: 15px;
  width: 100px;
}

.content-container {
  height: 600px;
}

.echarts-treeChart {
  /* min-width: calc(1200px - 48px); */
  width: calc(1200px - 48px);
  height: 600px;
}

.detail-container {
  position: relative;
  padding-top: 20px;
}

.detail-header-panel {
  position: relative;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  overflow: hidden;
  flex-wrap: wrap;
}

.panel-detail {
  position: relative;
  margin-right: 50px;
  margin-bottom: 15px;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.65);
}

.panel-detail span:last-child {
  font-size: 14px;
  color: #ffffff;
}

.fix-panel {
  flex: 0 0 100%;
  text-align: left;
}

.detail-body-panel {
  position: inherit;
  margin-top: 60px;
}

.time-panel-list {
  position: relative;
  border-bottom: 3px solid #000;
  display: flex;
  justify-content: space-between;
  padding: 26px 72px;
}

.time-panel-list::before {
  content: url(../../../assets/img/common/left_arrow.png);
  width: 23px;
  height: 40px;
  position: absolute;
  bottom: -21px;
  left: -1px;
}

.time-panel-list::after {
  content: url(../../../assets/img/common/right_arrow.png);
  width: 23px;
  height: 40px;
  position: absolute;
  bottom: -21px;
  right: -1px;
}

.time-panel {
  font-size: 22px;
  font-weight: 600;
  color: #45a5e5;
  position: relative;
}

.time-panel::after {
  content: url(../../../assets/img/common/round.png);
  width: 26px;
  height: 26%;
  position: absolute;
  bottom: -24px;
  left: 50%;
  transform: translate(-50%, -50%);
}

.time-panel-detail {
  position: relative;
  width: 495px;
  height: 394px;
  background: #45a5e5;
  border-radius: 5px;
  margin-top: 40px;
  margin-left: 50px;
  padding: 35px 30px;
}

.time-panel-title {
  position: relative;
  display: flex;
  justify-content: flex-start;
  margin-bottom: 25px;
}

.time-panel-title > span {
  font-size: 60px;
  font-weight: normal;
  color: #ffffff;
}

.time-panel-title > div {
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
}

.time-panel-title > div > span {
  display: block;
  font-size: 22px;
  font-weight: 600;
  color: #ffffff;
}

.time-panel-num {
  display: flex;
  justify-content: space-between;
}

.time-Num-box {
  font-size: 14px;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.65);
}

.time-Num-box span {
  display: block;
  text-align: left;
  margin-bottom: 5px;
}

.time-img {
  position: relative;
  width: 100%;
  margin-top: 25px;
  text-align: left;
}

.time-img > span {
  display: block;
  font-size: 14px;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.65);
  margin-bottom: 5px;
  text-align: left;
}

.time-img > img {
  width: 175px;
  height: 216px;
}

.time-panel-detail > img {
  position: absolute;
  bottom: 0;
  right: 0;
}

.time-panel-detail::before {
  content: "";
  width: 0;
  height: 0;
  border-left: 16px solid transparent;
  border-right: 16px solid transparent;
  border-bottom: 16px solid #45a5e5;
  font-size: 0;
  line-height: 0;
  position: absolute;
  left: 62px;
  top: -8px;
  transform: translateY(-50%);
}
</style>